//
//  YFBToast.swift
//  YFBUIKit
//
//  Created by admin on 2025/9/5.
//

import UIKit

open class KBToast: UIView {

    public enum YFBToastShowLoc {
        case `default`
        case top
        case middle
        case bottom
    }
    private static let shared = KBToast()
    private let minWidth: CGFloat = 150 //视图最小宽度
    private let maxWidth: CGFloat = 265 //视图最大宽度
    private let hMargin: CGFloat = 11 //文本垂直间距
    private let vMargin: CGFloat = 23 //文本水平间距
    private var messageLabel: UILabel?
    private var completionBlock: (() -> Void)?
    private var location: YFBToastShowLoc = .default
    private var yOffset: CGFloat = 0
    /**
     弹框展示
     - parameter message: 提示语（必传）
     - parameter location: 弹框位置（不传默认屏幕底部1/3处展示）
     - parameter y: 根据位置偏移坐标（不传默认0；当设置位置top，则是按照顶部偏移；当设置位置bottom，则是按照底部位置偏移；default/middle该参数不生效）
     - parameter duration: 持续时间：秒（不传默认3秒，最低1秒）
     */
    open class func show(_ message: String, location: YFBToastShowLoc = .default, y: CGFloat = 0, duration: TimeInterval = 3, keyboardWindow: Bool = false, completion: (() -> Void)? = nil) {
    
        shared.location = location
        shared.yOffset = y
        shared.completionBlock = completion
        
        var superWindow = UIApplication.shared.keyWindow
        if keyboardWindow == true, let lastWindow = UIApplication.shared.windows.last {
            let lwNameStr = NSStringFromClass(type(of:lastWindow))
            if lwNameStr.isEmpty == false, lwNameStr == "UIRemoteKeyboardWindow" {
                superWindow = UIApplication.shared.windows.last!
            }
        }else{
            UIApplication.shared.keyWindow?.endEditing(true)
        }
       
        if (superWindow != nil) {
            superWindow!.addSubview(shared)
        }
        
        let screenSize = UIScreen.main.bounds.size
        
        //提示语 -> 文字大小
        let size: CGSize = shared.setMessageReturnViewSize(message)
    
        //增加文本，边框间距
        let viewWidth: CGFloat = size.width
        let viewHeight: CGFloat = size.height
        let viewX = screenSize.width / 2 - viewWidth / 2
        var viewY : CGFloat = 0
    

        switch location {
        case .top:
            viewY = y
            break
        case .middle:
            viewY = screenSize.height / 2 - viewHeight / 2
            break
        case .bottom:
            viewY = screenSize.height - viewHeight - y
            break
        default:
            viewY = screenSize.height / 3 * 2
            break
        }

        
        //更新坐标
        shared.frame = CGRect(x: viewX, y: viewY, width: viewWidth, height: viewHeight)
        shared.backgroundColor = UIColor.clear
        shared.setNeedsDisplay()
    
        //弹出动画
        KBAnimation.showAnimation(shared)
        NSObject.cancelPreviousPerformRequests(withTarget: shared, selector: #selector(hiddenToast), object: nil)
        shared.perform(#selector(hiddenToast), with: nil, afterDelay: (duration <= 0 ? 1 : duration))

    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        setUI()
    }
    
    //MARK: - 设置UI
    private func setUI() {
        
        let screenSize = UIScreen.main.bounds.size
        
        //增加文本，边框间距
        let viewWidth: CGFloat = self.frame.size.width
        let viewHeight: CGFloat = self.frame.size.height
        let viewX = screenSize.width / 2 - viewWidth / 2
        var viewY : CGFloat = 0
        let y = self.yOffset
        
        switch self.location {
        case .top:
            viewY = y
            break
        case .middle:
            viewY = screenSize.height / 2 - viewHeight / 2
            break
        case .bottom:
            viewY = screenSize.height - viewHeight - y
            break
        default:
            viewY = screenSize.height / 3 * 2
            break
        }
        self.frame = CGRect(x: viewX, y: viewY, width: viewWidth, height: viewHeight)
        
    }
    
    //隐藏弹框
    @objc func hiddenToast(){
        UIView.animate(withDuration: 0.3) {
            self.removeFromSuperview()
            self.completionBlock?()
        }
    }
    
    //MARK: - 设置文本
    private func setMessageReturnViewSize(_ message: String) -> CGSize {
        
        let lblMaxWidth = maxWidth - vMargin * 2
        let lblMinWidth = minWidth - vMargin * 2
        
        let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 15.0)]
        let message_NS = NSString(string: message)
        var lblSize = message_NS.boundingRect(with: CGSize(width: lblMaxWidth, height: 0.00),
                                           options: .usesLineFragmentOrigin,
                                           attributes: attributes,
                                           context: nil).size
        lblSize.width = (lblSize.width < lblMinWidth ? lblMinWidth : lblSize.width)
        
        
        if messageLabel == nil {
            messageLabel = UILabel()
            messageLabel!.font = UIFont(name: "PingFangSC-Regular", size: 13) ?? UIFont.systemFont(ofSize: 13.0)
            messageLabel!.textAlignment = .center
            messageLabel!.numberOfLines = 0
            messageLabel!.backgroundColor = UIColor.clear
            messageLabel!.textColor = UIColor.white
            messageLabel!.lineBreakMode = .byCharWrapping
            self.addSubview(messageLabel!)
        }
        messageLabel!.frame = CGRect(x: vMargin, y: hMargin, width: ceil(lblSize.width + 1), height: ceil(lblSize.height + 1))
        messageLabel!.text = message
        
        let retSize : CGSize = CGSize(width: ceil(lblSize.width + 1) + vMargin * 2, height: ceil(lblSize.height + 1) + hMargin * 2)
        return retSize
        
    }
    
    //MARK: - UIView
    open override func draw(_ rect: CGRect) {
        // Drawing code
    
        let width: CGFloat = self.frame.size.width
        let height: CGFloat = self.frame.size.height
        
        let radius: CGFloat = 10
        let context: CGContext = UIGraphicsGetCurrentContext()!

        context.move(to: CGPoint(x: radius, y: 0))
        context.addLine(to: CGPoint(x: width - radius, y: 0))
        context.addArc(center: CGPoint(x: width - radius, y: radius), radius: radius, startAngle: -0.5 * Double.pi, endAngle: 0.0, clockwise: false)
        
        context.addLine(to: CGPoint(x: width, y: height - radius))
        context.addArc(center: CGPoint(x: width - radius, y: height - radius), radius: radius, startAngle: 0.0, endAngle: 0.5 * Double.pi, clockwise: false)
        
        context.addLine(to: CGPoint(x: radius, y: height))
        context.addArc(center: CGPoint(x: radius, y: height - radius), radius: radius, startAngle: 0.5 * Double.pi, endAngle: Double.pi, clockwise: false)
        
        context.addLine(to: CGPoint(x: 0, y: radius))
        context.addArc(center: CGPoint(x: radius, y: radius), radius: radius, startAngle: Double.pi, endAngle: 1.5 * Double.pi, clockwise: false)

        context.setFillColor(UIColor(white: 0, alpha: 0.75).cgColor)
        context.drawPath(using: .fill)
        
    }

}
